<template>
  <div class="basic-info-wrapper">
    <div class="section-item gray car-model-1000 relative">
      <div class="flex">
        <car-info-block
          :carInfo="carInfo"
          :tags="[
            {
              type: 'warn',
              label: carInfo.operateStatusName,
            },
            ...(carInfo.currentStatusNameList || []),
          ]"
          :fieldList="[
            { label: '归属门店', prop: 'siteName' },
            { label: '归属车场', prop: 'libraryName' },
          ]"
        >
          <template #operate>
            <car-model-popup :modelId="carInfo.tenantModelId" popupContainer=".car-model-1000">
              <a-button class="operate-btn" type="outline">查看车型</a-button>
            </car-model-popup>
          </template>
        </car-info-block>
      </div>
    </div>
    <div class="section-item">
      <div class="car-source-wrapper flex justify-between items-end">
        <div class="description-item">
          <span class="description-item-label">车辆来源：</span>
          <span class="description-item-content">{{ carInfo.sourceName }}</span>
        </div>
      </div>
    </div>
    <div class="section-item gray" style="padding: 0 20px">
      <div class="section-item-content">
        <div class="flex page">
          <div class="page-title">结算信息</div>
          <div class="page-count" v-if="contractData?.useInstallment"
            >合计：<span class="num">{{ contractData?.contractAmount || 0 }}</span> 元</div
          >
          <a-button v-if="contractData.useInstallment" class="btn" type="primary" size="mini" @click="openPayPlanFn">查看付款计划</a-button>
        </div>
        <a-descriptions
          :size="size"
          :align="{ label: 'right' }"
          v-if="[1, 3, 4].includes(carInfo.source) && contractData.useInstallment == 1"
        >
          <a-descriptions-item label="是否分期">{{ contractData?.useInstallment ? '是' : '否' }}</a-descriptions-item>
          <a-descriptions-item label="购车日期">{{ contractData?.purchaseCarDate }}</a-descriptions-item>
          <a-descriptions-item label="购置税">{{ contractData?.purchaseTax || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="首付">{{ contractData?.initialAmount || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="尾款">{{ contractData?.balanceAmount || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="过户费">{{ contractData?.transferFee || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="运输费">{{ contractData?.transportationFee || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="保证金">{{ contractData?.earnestMoney || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="手续费">{{ contractData?.serviceChargeFee || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="期数">{{ contractData?.lnstalmentNum || '-' }}期</a-descriptions-item>
          <a-descriptions-item label="每期金额">{{ contractData?.amountPerPeriod || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="第一期付款日">{{ contractData?.lnstalmentFirstDate }}</a-descriptions-item>
        </a-descriptions>
        <a-descriptions
          :size="size"
          :align="{ label: 'right' }"
          v-if="[1, 3, 4].includes(carInfo.source) && contractData.useInstallment == 0"
        >
          <a-descriptions-item label="是否分期">{{ contractData?.useInstallment ? '是' : '否' }}</a-descriptions-item>
          <a-descriptions-item label="购车日期">{{ contractData?.purchaseCarDate }}</a-descriptions-item>
          <a-descriptions-item label="购置金额">{{ contractData?.purchaseAmount || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="购置税">{{ contractData?.purchaseTax || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="过户费">{{ contractData?.transferFee || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="运输费">{{ contractData?.transportationFee || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="保证金">{{ contractData?.earnestMoney || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="手续费">{{ contractData?.serviceChargeFee || 0 }}元</a-descriptions-item>
        </a-descriptions>
        <a-descriptions :size="size" :align="{ label: 'right' }" v-if="[2].includes(carInfo.source) && contractData.useInstallment == 1">
          <a-descriptions-item label="是否分期">{{ contractData?.useInstallment ? '是' : '否' }}</a-descriptions-item>
          <a-descriptions-item label="借入日期">{{ contractData?.purchaseCarDate }}</a-descriptions-item>
          <a-descriptions-item label="首付">{{ contractData?.initialAmount || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="尾款">{{ contractData?.balanceAmount || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="期数">{{ contractData?.lnstalmentNum || '-' }}期</a-descriptions-item>
          <a-descriptions-item label="每期金额">{{ contractData?.amountPerPeriod || 0 }}元</a-descriptions-item>
          <a-descriptions-item label="第一期付款日">{{ contractData?.lnstalmentFirstDate }}</a-descriptions-item>
        </a-descriptions>
        <a-descriptions :size="size" :align="{ label: 'right' }" v-if="[2].includes(carInfo.source) && contractData.useInstallment == 0">
          <a-descriptions-item label="是否分期">{{ contractData?.useInstallment ? '是' : '否' }}</a-descriptions-item>
          <a-descriptions-item label="借入日期">{{ contractData?.purchaseCarDate }}</a-descriptions-item>
          <a-descriptions-item label="借调费">{{ contractData?.purchaseAmount || 0 }}元</a-descriptions-item>
        </a-descriptions>
      </div>
      <div class="section-item-content" style="border-top: 1px solid #f2f3f5">
        <div class="flex page">
          <div class="page-title">合同信息</div>
        </div>
        <a-descriptions :size="size" :align="{ label: 'right' }">
          <a-descriptions-item label="合同编号">{{ contractData?.contractNo }}</a-descriptions-item>
          <a-descriptions-item label="合同开始日期">{{ contractData?.contractSignDate }}</a-descriptions-item>
          <a-descriptions-item label="合同结束日期">{{ contractData?.contractEndDate }}</a-descriptions-item>
          <a-descriptions-item label="合同附件">
            <div v-if="contractData?.contractFileUrl">
              <template v-if="getFileSuffix(contractData)">
                <a class="operate-list" @click="filePreview(contractData.contractFileUrl, contractData.contractFileName)">点击查看</a>
              </template>
              <a class="operate-list" v-else @click="onClick"> 点击查看 </a>
              <a-image-preview :src="contractData?.contractFileUrl" v-model:visible="visible" />
            </div>
          </a-descriptions-item>
          <a-descriptions-item v-if="carInfo.source === 2" label="借调同行">
            {{ contractData?.supplierName }}
          </a-descriptions-item>
          <a-descriptions-item v-else label="汽车销售">{{ contractData?.supplierName }}</a-descriptions-item>
          <a-descriptions-item label="收款账号">{{ contractData?.receiveAccount }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </div>
    <div class="section-item" style="margin-top: 0">
      <div class="section-item-content">
        <a-descriptions :size="size" :align="{ label: 'right' }">
          <a-descriptions-item label="车辆颜色">{{ carInfo?.carColor }}</a-descriptions-item>
          <a-descriptions-item label="GPS设备">{{ carInfo?.vehicleStrList }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </div>
    <a-divider :margin="16" />
    <div class="section-item">
      <div class="section-item-header">行驶证信息</div>
      <div class="section-item-content">
        <a-descriptions :size="size" :align="{ label: 'right' }">
          <a-descriptions-item label="证件图示">
            <div
              :class="['view-photo', 'mr-3', { 'no-photo': !carInfo.driveImgFrontFileId }]"
              @click="previewFn(carInfo.driveImgFrontFileId)"
              >{{ `行驶证正页${!carInfo.driveImgFrontFileId ? '暂无照片' : ''}` }}</div
            >
            <div :class="['view-photo', { 'no-photo': !carInfo.driveImgBackFileId }]" @click="previewFn(carInfo.driveImgBackFileId)">{{
              `行驶证副页${!carInfo.driveImgBackFileId ? '暂无照片' : ''}`
            }}</div>
          </a-descriptions-item>
          <a-descriptions-item label="车头照" :span="2">
            <div :class="['view-photo', { 'no-photo': !carInfo.carHeadFileId }]" @click="previewFn(carInfo.carHeadFileId)">
              {{ `${!carInfo.carHeadFileId ? '暂无照片' : '查看照片'}` }}
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="车架号-车辆识别代码">{{ carInfo?.vin }}</a-descriptions-item>
          <a-descriptions-item label="发动机号">{{ carInfo?.engineNum }}</a-descriptions-item>
          <a-descriptions-item label="车牌颜色">{{ carInfo?.licenseNoColorName }}</a-descriptions-item>
          <a-descriptions-item label="品牌型号">{{ carInfo?.brandModel }}</a-descriptions-item>
          <a-descriptions-item label="行驶证所属人姓名">{{ carInfo?.driveNatureOwner }}</a-descriptions-item>
          <a-descriptions-item label="住址">{{ carInfo?.drivingAddress }}</a-descriptions-item>
          <a-descriptions-item label="注册日期">{{ carInfo?.registerDateStr }}</a-descriptions-item>
          <a-descriptions-item label="发证日期">{{ carInfo?.issuanceDateStr }}</a-descriptions-item>
          <a-descriptions-item label="使用性质">{{ carInfo?.driverUseNature }}</a-descriptions-item>
          <a-descriptions-item label="总质量">{{ carInfo.grossMass ? `${carInfo.grossMass}千克` : '' }}</a-descriptions-item>
          <a-descriptions-item label="整备质量">{{ carInfo.unladenMass ? `${carInfo.unladenMass}千克` : '' }}</a-descriptions-item>
          <a-descriptions-item label="外廓尺寸">{{
            carInfo.length && carInfo.width && carInfo.height ? `${carInfo.length} x ${carInfo.width} x ${carInfo?.height}` : ''
          }}</a-descriptions-item>
          <a-descriptions-item label="核定载人数">{{ carInfo.ac ? `${carInfo.ac}人` : '' }}</a-descriptions-item>
          <a-descriptions-item label="车辆类型">{{ carInfo?.driverCarType }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </div>
    <a-divider :margin="16" />
    <div class="section-item">
      <div class="section-item-header">运维信息</div>
      <div class="section-item-content">
        <a-descriptions :size="size" :align="{ label: 'right' }">
          <a-descriptions-item label="年检证">
            <img-link :value="carInfo.inspectionFileId" title="查看年检证" />
            <!-- <div :class="['view-photo', { 'no-photo': !carInfo.inspectionFileId }]" @click="previewFn(carInfo.inspectionFileId)">
              {{ `${!carInfo.inspectionFileId ? '暂无照片' : '查看照片'}` }} -->
            <!-- </div> -->
          </a-descriptions-item>
          <a-descriptions-item label="年检到期日">
            {{ carInfo?.planTime || '-' }}
            <a-button
              type="outline"
              size="mini"
              v-if="usePermission('svms:system:general:backlogRule.edit')"
              @click="onClickSystem('inspection')"
            >
              去配置年检预警
            </a-button>
            <div><carListModel :date="carInfo.planTime" /></div>
          </a-descriptions-item>
          <a-descriptions-item>&nbsp;</a-descriptions-item>
          <a-descriptions-item label="商业险保单">
            <img-link :value="carInfo.businessFileId" file title="查看商业险保单" />
            <!-- <div :class="['view-photo', { 'no-photo': !carInfo.businessFileId }]" @click="previewFn(carInfo.businessFileId)">
              {{ `${!carInfo.businessFileId ? '暂无照片' : '查看照片'}` }}
            </div> -->
          </a-descriptions-item>
          <a-descriptions-item label="商业险到期日">
            {{ carInfo?.businessEndDate || '-' }}
            <a-button
              type="outline"
              size="mini"
              v-if="usePermission('svms:system:general:backlogRule.edit')"
              @click="onClickSystem('insureBusinessDay')"
            >
              去配置商业险预警
            </a-button>
            <div><carListModel :date="carInfo.businessEndDate" /></div>
          </a-descriptions-item>
          <a-descriptions-item>&nbsp;</a-descriptions-item>
          <a-descriptions-item label="交强险保单">
            <img-link :value="carInfo.compulsoryFileId" file title="查看交强险保单" />
            <!-- <div :class="['view-photo', { 'no-photo': !carInfo.compulsoryFileId }]" @click="previewFn(carInfo.compulsoryFileId)">
              {{ `${!carInfo.compulsoryFileId ? '暂无照片' : '查看照片'}` }}
            </div> -->
          </a-descriptions-item>
          <a-descriptions-item label="交强险到期日">
            {{ carInfo?.compulsoryEndDate || '-' }}
            <a-button
              type="outline"
              size="mini"
              v-if="usePermission('svms:system:general:backlogRule.edit')"
              @click="onClickSystem('insureCompulsoryDay')"
            >
              去配置交强险预警
            </a-button>
            <div> <carListModel :date="carInfo.compulsoryEndDate" /></div>
          </a-descriptions-item>
          <a-descriptions-item>&nbsp;</a-descriptions-item>
          <a-descriptions-item label="车辆当前行驶里程">
            {{ unitVal(carInfo?.totalMileage, '公里') }}
          </a-descriptions-item>
          <a-descriptions-item label="下次保养里程">
            {{ isValid(carInfo?.estimatedKilometre) ? carInfo?.estimatedKilometre : '-' }} 公里
            <a-button
              type="outline"
              size="mini"
              v-if="usePermission('svms:system:general:backlogRule.edit')"
              @click="onClickSystem('maintenance')"
            >
              去配置保养预警信息
            </a-button>
            <carListModel v-if="isValid(carInfo?.estimatedKilometre)" type="mileage" :record="carInfo" />
          </a-descriptions-item>
          <a-descriptions-item label="下次保养日期">
            {{ carInfo?.estimatedTime || '-' }}
            <a-button
              type="outline"
              size="mini"
              v-if="usePermission('svms:system:general:backlogRule.edit')"
              @click="onClickSystem('maintenance')"
            >
              去配置保养预警信息
            </a-button>
            <div><carListModel :date="carInfo?.estimatedTime" /></div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </div>
    <a-divider :margin="16" />
    <div class="section-item" v-if="userStore.enterpriseDetail.tboxEnabled == 1">
      <div class="section-item-header">车载BOX设备信息</div>
      <div class="section-item-content">
        <a-descriptions :size="size" :align="{ label: 'right' }">
          <a-descriptions-item label="设备状态">{{ carInfo?.tboxEquipmentStatusName }}</a-descriptions-item>
          <a-descriptions-item label="车载BOX车辆当前公里数">{{
            carInfo.tboxCurrentMileage != null ? carInfo.tboxCurrentMileage + '公里' : '-' + '公里'
          }}</a-descriptions-item>
          <a-descriptions-item label="车载BOX车辆当前油(电)量">{{
            carInfo?.tboxCurrentOil != null ? carInfo?.tboxCurrentOil : '-'
          }}</a-descriptions-item>
          <a-descriptions-item label="设备供应商">{{ carInfo?.tboxVehicleFirm }}</a-descriptions-item>
        </a-descriptions>
      </div>
      <a-divider :margin="16" />
    </div>
    <div class="section-item" v-if="userStore.enterpriseDetail.hrhcEtcEnabled == 1 || userStore.enterpriseDetail.quantumEtcEnabled == 1">
      <div class="section-item-header">ETC设备信息</div>
      <div class="section-item-content">
        <a-descriptions :size="size" :align="{ label: 'right' }">
          <a-descriptions-item label="设备是否激活">{{ carInfo?.etcEquipmentActivationName }}</a-descriptions-item>
          <a-descriptions-item label="ETC设备号">{{ carInfo?.etcEquipmentNo || '无设备' }}</a-descriptions-item>
          <a-descriptions-item label="ETC卡号">{{ carInfo?.etcCardNo || '无设备' }}</a-descriptions-item>
          <a-descriptions-item label="设备是否在线">{{ carInfo?.etcEquipmentOnLineName }}</a-descriptions-item>
          <a-descriptions-item label="硬件连接状态">{{ carInfo?.etcHardwareStatusName }}</a-descriptions-item>
          <a-descriptions-item label="设备工作状态">{{ carInfo?.etcWorkStatusName }}</a-descriptions-item>
        </a-descriptions>
      </div>
      <a-divider :margin="16" />
    </div>
    <div class="section-item" v-if="carInfo.disposalType !== 0">
      <div class="section-item-header">处置信息</div>
      <div class="section-item-content">
        <a-descriptions :size="size" :align="{ label: 'right' }">
          <a-descriptions-item label="处置类型">{{ carInfo?.disposalTypeName }}</a-descriptions-item>
          <a-descriptions-item v-if="carInfo.disposalType == 1" label="出售时间">{{ carInfo?.disposalTimeStr || '-' }}</a-descriptions-item>
          <a-descriptions-item v-if="carInfo.disposalType == 2" label="报废时间">{{ carInfo?.disposalTimeStr || '-' }}</a-descriptions-item>
          <a-descriptions-item v-if="carInfo.disposalType == 3" label="归还时间">{{ carInfo?.disposalTimeStr || '-' }}</a-descriptions-item>
          <a-descriptions-item v-if="carInfo.disposalType == 4" label="下线时间">{{ carInfo?.disposalTimeStr || '-' }}</a-descriptions-item>
          <a-descriptions-item v-if="carInfo.disposalType == 1" label="出售金额">
            {{ unitVal(carInfo?.disposalAmount) }}
          </a-descriptions-item>
          <a-descriptions-item v-if="carInfo.disposalType == 2" label="补贴金额">
            {{ unitVal(carInfo?.disposalAmount) }}
          </a-descriptions-item>
          <a-descriptions-item label="备注">{{ carInfo?.disposalRemark || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </div>
    <!-- 查看付款计划 -->
    <car-payment-plan-modal ref="carPaymentPlanModalRef" />
    <!-- 查看车辆图片 -->
    <a-image-preview-group
      v-model:visible="previewVisible"
      v-model:current="previewCurrent"
      :maskClosable="false"
      :srcList="previewList"
      @close="onClosePreviewFn"
    />
    <!-- 预览pdf -->
    <pdf-viewer
      :url="pdfViewInfo.url"
      :title="pdfViewInfo.title"
      v-model:visible="pdfViewInfo.show"
      @close="Object.assign(pdfViewInfo, { ...PDFDefaultAttr })"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, reactive } from 'vue'
  import { findPayableListById } from '@/api/asset/car'
  import carModelPopup from '../../components/car-model-popup.vue'
  import carPaymentPlanModal from '../../components/car-payment-plan-modal.vue'
  import carListModel from '../../components/car-list-model.vue'
  import { unitVal } from '@/utils'
  import useUserStore from '@/store/modules/user'
  import { isValid } from '@/utils'

  const props = defineProps({
    carInfo: Object,
  })

  // 合同信息
  const contractData = computed(() => {
    return props.carInfo?.contractCarPurchaseEditVo || {}
  })

  // 获取商户是否开启etc和tbox
  const userStore = useUserStore()
  userStore.setEpDetail()
  // pdf预览
  import { PDFDefaultAttr } from '@/components/pdf-viewer/const'
  const pdfViewInfo = reactive({ ...PDFDefaultAttr })

  import useNavigate from '@/hooks/useNavigate'
  import { usePermission } from '@/hooks/usePermission'

  const { navigateTo } = useNavigate()
  const size = ref('medium')

  const visible = ref(false)

  const onClickSystem = (type) => {
    console.log('🐳 > onClickSystem > type:', type)
    navigateTo(`/system/general/backlog-rule?status=edit&type=${type}`)
  }

  const onClick = () => {
    visible.value = true
  }
  // 文件预览
  const filePreview = (url, name) => {
    // pdf预览
    let fileName = name.split('.').pop().toLowerCase()
    // if (fileName == 'pdf') {
    //   return Object.assign(pdfViewInfo, {
    //     url: url,
    //     title: name,
    //     show: true,
    //   })
    // }
    window.open(url)
  }
  const carPaymentPlanModalRef = ref()
  const openPayPlanFn = () => {
    findPayableListById({ id: contractData.value.id }).then((res) => {
      const result = res.result
      carPaymentPlanModalRef.value.open(result)
    })
  }

  const getFileSuffix = (data) => {
    if (!data) return false
    let suffix = data.contractFileUrl.substring(data.contractFileUrl.lastIndexOf('.') + 1)
    if (suffix === 'pdf' || suffix === 'PDF' || suffix === 'doc' || suffix === 'docx') {
      return true
    }
    return false
  }

  // 预览
  const previewVisible = ref(false)
  const previewCurrent = ref(0)
  const previewList = ref<string[]>([])
  const previewFn = (vals: string[] | string) => {
    if (vals) {
      previewVisible.value = true
      if (Array.isArray(vals)) {
        previewList.value = vals.map((val) => {
          return `${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${val}`
        })
      } else {
        previewList.value = [`${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${vals}`]
      }
    }
  }

  const onClosePreviewFn = () => {
    previewVisible.value = false
    previewList.value = []
    previewCurrent.value = 0
  }
</script>

<style lang="less" scoped>
  .basic-info-wrapper {
    .section-item {
      .section-item-header {
        color: #1d2129ff;
        font-weight: 500;
      }
      .section-item-content {
        padding: 20px 20px 0 20px;
      }
      .btn {
        margin-left: 16px;
      }
      &.gray {
        background-color: rgba(var(--gray-1), 0.5) !important;
        border-radius: 0px 0px 0px 0px;
        .section-item-content {
          padding: 20px 20px 12px 20px;
        }
      }
    }
    .section-item + .section-item {
      margin-top: 16px;
    }
  }
  .view-photo {
    color: #1890ff;
    display: inline-block;
    cursor: pointer;
    text-decoration: underline;
  }
  .no-photo {
    color: #9ca3af;
    text-decoration: none;
    cursor: unset;
  }
  .description-item {
    font-size: 14px;
    .description-item-label {
      color: var(--color-text-3);
    }
    .description-item-content {
      color: var(--color-text-1);
    }
  }
  .view-file-link {
    font-size: 14px;
    color: rgb(var(--primary-6));
    text-decoration: underline;
    text-underline-offset: 3px;
    cursor: pointer;
  }
  .page {
    margin-bottom: 7px;
    .page-title {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 16px;
      color: #1d2129;
      line-height: 24px;
    }
    .page-count {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #4e5969;
      margin-left: 17px;
      line-height: 22px;
    }
    .num {
      color: #1890ff;
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 18px;
      color: #1890ff;
      line-height: 22px;
    }
  }
  .contractFile {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #1890ff;
    line-height: 22px;
    text-align: left;
    font-style: normal;
    text-decoration-line: underline;
    text-transform: none;
  }
  .operate-list {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #1890ff;
    border-bottom: 1px solid #1890ff;
    cursor: pointer;
  }
</style>
